#include <stdio.h>
#include <string.h>
#include <stdint.h>

#include <fdb.h>
#include <fdb-helpers.h>

int main(int argc, char *argv[]) {
	char buffer[1024];
	FILE *fp;
	database_t *database;
	transaction_t *transaction;
	query_t *query;
	result_e result;
	helper_sequence_t sequence;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s <database> <source data>", argv[0]);
		return 1;
	}

	fp = fopen(argv[2], "r");
	if (fp == NULL)
		return 1;

	database = database_open(argv[1]);
	if (database == NULL)
		return 1;

	helper_sequence_init(&sequence);
	sequence.name = "data_pkey_sequence";
	sequence.step = 1;

	transaction = transaction_begin(database, READ_COMMITTED);
	query = query_new(transaction);

	query_prepare(query, QUERY_INSERT, "data");
	query_execute(query);
	while (!feof(fp)) {
		/* Retrieve new sequence value. */
		helper_sequence_step_sequence(transaction, "sequence", &sequence);
		
		/* Insert the data */
		fgets(buffer, 1023, fp);
		printf("Inserting: %lld\n", sequence.value);

		printf("buffer: %p '%s' %d\n", buffer, buffer, strlen(buffer));

		query_data_set(query, &sequence.value, sizeof(sequence.value), buffer, strlen(buffer));
		query_step(query);
	}
	query_finalize(query);

	query_destroy(query);

	transaction_commit(transaction);
	database_close(database);

	fclose(fp);

	return 0;
}


